package io.nio;

import framework.AbstractTest;
import utils.Log;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * Created by shane on 2018/5/20.
 *
 * nio的目标就是快速移动大量数据， 因此ByteBuffer的大小就显得尤为重要
 */
public class GetChannel extends AbstractTest {
    protected static final String TAG = GetChannel.class.getName();

    @Override
    public void test(String[] args) {
        super.test(args);

        String outPath = getDefOutputFile(args);

        try {
            FileChannel fc = new FileOutputStream(outPath).getChannel();
            fc.write(ByteBuffer.wrap("some data...".getBytes()));
            fc.close();

            fc = new RandomAccessFile(outPath, FILE_MODE_RW).getChannel();
            fc.position(fc.size());
            fc.write(ByteBuffer.wrap("some more...".getBytes()));
            fc.close();

            fc = new FileInputStream(outPath).getChannel();
            ByteBuffer buf = ByteBuffer.allocate(BSIZE);
            fc.read(buf);
            buf.flip();
            while (buf.hasRemaining()) {
                Log.v((char)buf.get());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected String getTag() {
        return TAG;
    }

}
